/**
 * 
 * 
 * 接单管理
 */
var iFrameName = this.name;
$(function(){
	OrderReceiving.init();
});

var queryType = 0;
var alarmType = null;
var OrderReceiving = {
	param: {},
	init: function(){
		var me = this;
		me.initQueryTime();
		me.initTableTitle();
		//加载平台下拉框
		me.loadprocessType();
		//加载车辆下拉框
		me.loadVehicleAlarm();
		//加载司机下拉框
		me.loadAlarmType();
	},
	getToday : function(){
		var todayDate = new Date();
        var yyyy = todayDate.getFullYear();
        var mm = todayDate.getMonth()+1;
        var dd = todayDate.getDate();  
        if (mm.toString().length == 1) {
	        mm = '0' + mm;
	    }
	    if (dd.toString().length == 1) {
	        dd = '0' + dd;
	    }
        return yyyy + '-' + mm + '-' + dd;
	},
    initQueryTime:function(){
        var todayDate = new Date();
        //var beforeDate = new Date(todayDate-86400000*1); //前一天
	    var yyyy = todayDate.getFullYear(), mm = (todayDate.getMonth() + 1).toString(), dd = todayDate.getDate().toString();
        $("#inputStartDate").val(yyyy + '-' + mm + '-' + dd);
        $("#inputEndDate").val(yyyy + '-' + mm + '-' + dd);
    },
	    // 获取查询条件
    getParams: function () {
    	var license = $('#license').val();
    	var alarmType = $('#alarmType').val();
    	var processType = $('#processType').val();
    	var inputStartDate = $('#inputStartDate').val();
    	var inputEndDate = $('#inputEndDate').val();
        var params = [{
        	name: 'alarmType',
            value: alarmType
        }, {
        	name: 'license',
        	value: license
        }, {
            name: 'processType',
            value: processType
        }, {
            name: 'inputStartDate',
            value: inputStartDate
        }, {
            name: 'inputEndDate',
            value: inputEndDate
        }];
        return params;
    },
    //车辆下拉框
    loadVehicleAlarm :function(){
    	$("#license").select2({
	        theme: "default",
	        allowClear: true,
	        placeholder: "全部车辆",
	        ajax:{
	            url:appCtx + "/system/common/selectVehicle.html",
	            dataType:"json",
	            delay:250,
	            data:function(params){
	                return {
	                    name: params.term,
	                    page: params.page || 1
	                };
	            },
	            cache:true,
	            processResults: function (res, params) {
			    	if(res){
			    		var options = [];
			    		var option = {"id":" ", "text":"全部车辆"};
			    		options.push(option);
	    				$.each(res,function(index,obj) {
	    					var option = {"id":obj.vehicle_no, "text":obj.vehicle_no};
    	                    options.push(option);
	    				});
    	                return {
    	                	results: options,
    	                    pagination: {
    	                        more:false
    	                    }
    	                };
			    	}
	            },
	            escapeMarkup: function (markup) { return markup; },
	            minimumInputLength: 1
	        }
    	});
	},
    //报警类型下拉框
    loadAlarmType :function(){
    	$('#alarmType').select2({
    		theme: "default",
 	        allowClear: true,
 	        placeholder: "全部报警类型",
 	        ajax:{
 	            url:appCtx + "orderReceiving/OrderReceiving/loadAlarmType.html?time="+ new Date().getTime(),
 	            dataType:"json",
 	            delay:250,
 	            async : true,
 	            data:function(params){
 	                return {
 	                    name: params.term,
 	                    page: params.page || 1
 	                };
 	            },
 	            cache:true,
 	            processResults: function (res, params) {
 			    	if(res){
 			    		var options = [];
 			    		var option = {"id":" ", "text":"全部报警类型"};
 			    		options.push(option);
 	    				$.each(res,function(index,obj){
 	    					var option = {"id":obj.id, "text":obj.name};
     	                    options.push(option);
 	    				});
     	                return {
     	                	results: options,
     	                    pagination: {
     	                        more:false
     	                    }
     	                };
 			    	}
 	            },
 	           escapeMarkup: function (markup) { return markup; },
	           minimumInputLength: 1
 	        }
    	})
		/*$("#alarmType").on("select2:select",function(e){
			$('#alarmType0').val(e.params.data.id);
		});*/
	},
	//加载处理类型下拉框
	loadprocessType:function(){
		$('#processType').select2();
	},
    initTableTitle:function(){
    	var heig = $('#table').height(); 
    	$("#objTable").flexigrid({
    			url:appCtx+'orderReceiving/OrderReceiving/queryTable.html?time='+ new Date().getTime(),
	            dataType : 'json',
	            params:OrderReceiving.getParams(),
	            colModel : OrderReceiving.getcolumn() ,
	            usepager : true,// 是否分页，默认为true。
	            resizable : false,
				sortname : 'alarm_time',// 第一次加载数据时排序列
				sortorder : "desc",// 第一次加载数据时排序类型
				usepager : true,// 是否分页，默认为true
				//minheight: 50, //列的最小高度
				nowrap: true, //是否不换行
				showToggleBtn : false,
				showTableToggleBtn : true,// 是否显示收起/打开按钮,默认不显示。
				useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
				rp : 10,// 每页记录数，默认为10
				rpOptions: [10, 20, 50, 100], // 每页结果数
				checkbox : true,// 是否要多选框,默认为false。
				rowId : 'id',// 多选框绑定行的id,只有checkbox : true时才有效。
	            height:$(window).height() - 240,
	            widthType:'%',
	            width:$('.detail-report').width(),
	            OnloadSuccess:function(){
	            }
	         });	 
    },
	tableReload: function(){
		$("#objTable").flexOptions({
			newp :1,// 设置起始页
			url : appCtx+'orderReceiving/OrderReceiving/queryTable.html?time='+ new Date().getTime(),
			params : OrderReceiving.getParams()
		}).flexReload();
	},
    getcolumn:function(){
    	return [{
            display : '车牌号',
            name : 'vehicle_no',
            width : 6,
            sortable:false,
            showTitle:true,
            align : 'left'
        },{
            display : '颜色',
            width : 4,
            name : 'vehicle_color_name',
            align : 'left',
            sortable:false,
        },{
        	display : '业户名称',
        	name : 'enterprise_name',
        	width : 10,
        	align : 'left',
        	showTitle:true,
        	sortable:false
        },{
            display : '平台名称',
            name : 'platform_name',
            width : 10,
            align : 'left',
            showTitle:true,
            sortable:false,
        },{
        	display : '报警类型',
        	name : 'alarm_type_name',
        	width : 5,
        	align : 'left',
        	showTitle:true,
        	sortable:false
        },{
            display : '报警来源',
            name : 'alarm_src',
            width : 5,
            align : 'left',
            sortable:false,
            paramcolnames:['alarm_src'],
            handlefunction :function(alarm_src){
            	if(alarm_src == 1){
            		return "终端";
            	}else if(alarm_src == 2){
            		return "企业平台";
            	}
            }
        },{
            display : '报警时间',
            name : 'alarm_time',
            width : 10,
            align : 'left',
            sortable:false,
            paramcolnames:['alarm_time'],
            handlefunction :function(alarm_time){
            	return  global.getTime(new Date(Number(alarm_time)));
            }
        },{
            display : '处理时间',
            name : 'handle_time',
            width : 10,
            align : 'left',
            sortable:false,
            paramcolnames:['handle_time'],
            handlefunction :function(handle_time){
            	if(handle_time!=null&&handle_time!=''){
            		return  global.getTime(new Date(Number(handle_time)));
            	}else{
            		return '';
            	}
            }
            
        },{
            display : '处理类型',
            name : 'handle_type',
            width : 5,
            align : 'left',
            sortable:false,
            paramcolnames:['handle_type'],
            handlefunction :function(handle_type){
            	return handle_type==null||handle_type==''?'未处理':(handle_type=='1'||handle_type==1?'系统处理':'人工处理');
            }
            
        },{
            display : '处理结果',
            name : 'handle_remark',
            width : 25,
            align : 'left',
            showTitle:true,
            sortable:false
        },{
            display : '报警位置',
            name : 'alarm_location',
            width : 5,
            align : 'left',
            sortable:false,
            paramcolnames:['vehicle_no','vehicle_color','alarm_time','lng','lat'],
            handlefunction : function(vehicle_no,vehicle_color,alarm_time,lng,lat){
			 if(lng == undefined || lng == "undefined"){
				 lng = 0;
			 }
			 if(lat == undefined || lat == "undefined"){
				 lat = 0;
			 }
			 var vehicle_no_color = encodeURI(vehicle_no + "_" + vehicle_color);
			 return "<a target='_blank' href='" + appCtx + "/report/alarmSyn/toVehiclePosition.html?vehicle_no_color=" + vehicle_no_color + "&lng=" + lng + "&lat=" + lat + "&alarm_time=" + alarm_time + "'>查看地图</a>";
		 }
        },{
            display : '操作',
            name : 'option',
            width : 5,
            align : 'left',
            sortable:false,
            paramcolnames:['vehicle_no','vehicle_color','alarm_type','alarm_src','alarm_time','platform_id','platform_name','enterprise_id','enterprise_name','area_id','alarm_type_name'],
            handlefunction :function(vehicle_no,vehicle_color,alarm_type,alarm_src,alarm_time,platform_id,platform_name,enterprise_id,enterprise_name,area_id,alarm_type_name){
            	return "<a href='javaScript:;' onclick=\"OrderReceiving.show('"+vehicle_no+"','"+vehicle_color+"','"+alarm_type+"','"+alarm_src+"','"+alarm_time+"','"+userName+"','"+platform_id+"','"+platform_name+"','"+enterprise_id+"','"+enterprise_name+"','"+area_id+"','"+alarm_type_name+"')\" >报警处理</a>"
            }
        }];
    },
	show:function(vehicle_no,vehicle_color,alarm_type,alarm_src,alarm_time,handle_name,platform_id,platform_name,enterprise_id,enterprise_name,area_id,alarm_type_name){
    	$('#Title').html("处理报警");
    	$.ajax({
    		url:appCtx+'orderReceiving/OrderReceiving/queryalarmhandle.html',
    		type:'post',
    		data:{'vehicle_no':vehicle_no,'vehicle_color':vehicle_color,'alarm_type':alarm_type,'alarm_time':global.getTime(new Date(Number(alarm_time)))},
    		dataType:'json',
    		async:false,
    		success:function(data){
    			console.log(data);
    			var tips='';
    			if(data!=null){
    				var str = null;
    				var obj = data.notice_obj.split(',');
    				var notice_obj=null;
    				$.each(obj,function(index,vo){
    					str = (vo==1||vo=='1'?'司机':vo==2||vo=='2'?'监控人员':vo==3||vo=='3'?'负责人':vo==4||vo=='4'?'运营商':vo==5||vo=='5'?'管理机构':null);
    					notice_obj = notice_obj==null?(str=null?'':str):notice_obj+(str==null?'':','+str);
    				});
    				tips = '*提示：该报警于['+global.getTime(new Date(Number(data.handle_time)))+']已被系统处理并通知了['+notice_obj+']';
        	    	
    			}
    			$('#handleTips').text(tips);
    		}
    	});
    	var param = new Object();
    	param.vehicle_no=vehicle_no;
    	param.vehicle_color=vehicle_color;
    	param.alarm_type=alarm_type;
    	param.alarm_src=alarm_src;
    	param.alarm_time=alarm_time;
    	param.handle_name=handle_name;
    	param.platform_id=platform_id;
    	param.platform_name=platform_name;
    	param.enterprise_id=enterprise_id;
    	param.enterprise_name=enterprise_name;
    	param.area_id=area_id;
    	param.alarm_type_name=alarm_type_name;
    	paramMap=param;
    	$('#win').modal('show');
    	$('#iframe').attr('src',appCtx+'orderReceiving/OrderReceiving/tosaveHandleDeatils.html');
	},
	saveHandleDeatils:function(){
		$.ajax({
			url:appCtx+'orderReceiving/OrderReceiving/saveHandleDetail.html',
			dataType:'json',
			data:$("#iframe").contents().find("#saveHandle").serialize(),
			type:'post',
			ansync:true,
			success:function(data){
				if(data.result=='success'){
					$('#win').modal('hide');
					global.ajaxLoading.pop('处理成功！',false,2000);
					OrderReceiving.tableReload();
				}else{
					global.ajaxLoading.pop(data.tips,false,2000);
				}
			}
		});
	},
	

	 //显示导出窗口
    doExportModal:function (msg,iFrameName,callback){
		      mFrameName = iFrameName;
		      mDialogCallback = callback;
		    $("#exportTitle").html(msg);
			$("#exportModal").modal('show');
			
		},
    exportExcel:function(){
		var me=OrderReceiving;
		var options = $("#objTable").getOptions();
		//总记录数
		var total = options.total;
		if(total==0){
			me.ajaxLoading("无导出数据",false,2000);
			return;
		}
		var pages = options.pages;
		//设置默认的开始结束页
		$("#StartPageIndex").val(1);
		$("#EndPageIndex").val(pages);
		me.doExportModal("导出表格",iFrameName,"OrderReceiving.exportCarExcel()");   
	},
    exportCarExcel:function(){
        var me = this;
    	$("#exportModal").modal('hide');
		var header1 = JSON.stringify(OrderReceiving.getcolumn());
		console.log('header1:'+header1);
		var header2 = JSON.parse(header1);
		console.log('header2:'+header2);
        //开始页数
        var StartPage=window.parent.$("#StartPageIndex").val();
        //结束页数
        var EndPage=window.parent.$("#EndPageIndex").val();
        var validate=true;
        var msg="";

        if(!StartPage || StartPage<=0){
            msg+="起始页不能为空或者小于等于0";
            validate=false;
        }
        if(!EndPage || EndPage<=0){
            msg+="结束页不能为空或者小于等于0";
            validate=false;
        }
        if(StartPage && EndPage &&EndPage<StartPage){
            msg+="结束页要大于起始页";
            validate=false;
        }

        if(!validate){
            me.ajaxLoading(msg,false,2000);
            return;
        }

		var options = $("#objTable").getOptions();
		//总记录数
		var total = options.total;
		var pagesize = options.rp;
		
		
		var headerWidth = $(".chart").width()*2;
		for(var i=0;i<header2.length;i++){
			header2[i].width = Math.ceil(headerWidth / 100 * header2[i].width);
		}
		header2.splice(header2.length-2,2);
		var header3 = JSON.stringify(header2);
		//表头
		var colModelList=new Array();
		colModelList.push(header3);
		var colModel= $.toJSON(colModelList);
    	var license = $('#license').val();
    	var alarmType = $('#alarmType').val();
    	var processType = $('#processType').val();
    	var inputStartDate = $('#inputStartDate').val();
    	var inputEndDate = $('#inputEndDate').val();
		var param =  {
				colModel:colModel,
	            alarmType:alarmType,
	        	license:license,
	            processType:processType,
	            inputStartDate:inputStartDate,
		        inputEndDate:inputEndDate,
				StartPage:StartPage,
				EndPage:EndPage,
				sortName:"alarm_time",
				pagesize:pagesize,
				title:"报警处理表",
		};
		post(appCtx+'orderReceiving/OrderReceiving/export.html',param);
    }

};
